/*
$(document).ready(function () {
    $("#fileCodeInput").change(function () {
       console.log($("#fileCodeInput").val())
    });
});
 */

var notyf = new Notyf({delay:3000});
var preCode = '000000';
var fileCode;
var filePass;
var fileOriginName;
var fileURI;
var hasDownload;
function getFile() {
    var hasFile;
    var hasPass;

    fileCode = $("#fileCodeInput").val();

    if (preCode != fileCode && fileCode.length == 6) {
        // console.log($("#fileCodeInput").val());
        preCode = fileCode;

        checkFile(hasFile, hasPass);
        // console.log(hasFile + ", " + hasPass);

    }
}

function getFileURI(fileCode, filePass, hasDownload) {
    hasDownload = false;

    $.ajax({
        url: "/api/getFileURI",
        traditional: true, // 使用传统解析，重要！
        type: "POST",
        data: {"fileCode": fileCode, "filePass": filePass},
        dataType: "json",
        success: function (res) {
            if (res.code == 0) {
                notyf.confirm('file download.');
                hasDownload = true;

                fileURI = res.data.fileURI;
                fileOriginName = res.data.fileOriginName;

                $("#fileURIInfo").attr("href", fileURI);
                $("#fileURIInfo").attr("download", fileOriginName);
                $("#file_code_finish").text(fileCode);

                setTimeout(function () {
                    document.getElementById("finishModalLink").click();
                }, 1000);

                setTimeout(function () {
                    document.getElementById("fileURIInfo").click();

                    $("#fileCodeInput").val('');
                }, 2000);
            }
        },
        error: function () {
            notyf.alert('server load fail.');
        }
    });
}

function checkFile(hasFile, hasPass) {
    $.ajax({
        url: "/api/checkExistenceAndHasPass",
        traditional: true, // 使用传统解析，重要！
        type: "POST",
        data: {"fileCode": fileCode},
        dataType: "json",
        success: function (res) {
            if (res.code == 0) {
                hasFile = res.data.fileExistence;
                hasPass = res.data.fileHasPass;

                if (hasFile == false) {
                    notyf.alert('file does not exist');
                }

                if (hasFile == true && hasPass == false) {
                    getFileURI(fileCode, '', hasDownload);
                }
                if (hasFile == true && hasPass == true) {
                    filePass = prompt('此文件已加密，请输入文件密码');
                    getFileURI(fileCode, filePass, hasDownload);

                    if (hasDownload == false) {
                        notyf.alert('password incorrect.');
                    }
                }
            }
        },
        error: function () {
            notyf.alert('server load fail.');
        }
    });
}